# powershell_demo.ps1 - SecureConfig命令行工具的PowerShell演示脚本

# 设置主密钥环境变量
# 实际使用时请替换为您的真实密钥
$env:SECURECONFIGMASTERKEY = "your_master_key_here"

# 计时开始
$startTime = Get-Date

# 执行secureconfig命令并返回结果
function Invoke-SecureconfigCommand {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Command,
        
        [Parameter(ValueFromRemainingArguments=$true)]
        [string[]]$Arguments
    )
    
    $fullCommand = @("secureconfig", $Command) + $Arguments
    Write-Host "正在执行命令: $($fullCommand -join ' ')" -ForegroundColor Yellow
    
    try {
        $output = & secureconfig $Command $Arguments 2>&1
        
        # 检查命令是否成功
        if ($LASTEXITCODE -eq 0) {
            # 尝试解析JSON输出
            try {
                # 查找JSON开始的位置
                $jsonStart = $output.IndexOf('{')
                if ($jsonStart -ge 0) {
                    $jsonOutput = $output.Substring($jsonStart)
                    return ConvertFrom-Json -InputObject $jsonOutput
                }
                return ConvertFrom-Json -InputObject $output
            }
            catch {
                return @{ output = $output; status = "success" }
            }
        }
        else {
            # 尝试从错误输出中解析JSON
            try {
                # 查找JSON开始的位置
                $jsonStart = $output.IndexOf('{')
                if ($jsonStart -ge 0) {
                    $jsonOutput = $output.Substring($jsonStart)
                    return ConvertFrom-Json -InputObject $jsonOutput
                }
            }
            catch {}
            
            return @{ status = "error"; message = "命令执行失败 (退出码 $LASTEXITCODE): $output" }
        }
    }
    catch {
        return @{ status = "error"; message = "命令执行异常: $_" }
    }
}

# 打印结果
function Write-Result {
    param(
        [string]$Title,
        [object]$Result
    )
    
    Write-Host "`n==== $Title ====" -ForegroundColor Cyan
    if ($Result.status -eq "success") {
        $Result | ConvertTo-Json -Depth 10
    }
    else {
        Write-Host "失败: $($Result.message)" -ForegroundColor Red
    }
}

Write-Host "`n===== 第一部分: 常规加解密操作 =====" -ForegroundColor Cyan

# 1. 创建 json 配置文件
$jsonName = "demo_json"
Write-Host "创建 json 配置文件: $jsonName"
$result = Invoke-SecureconfigCommand -Command "create" -Arguments $jsonName, "--type", "json", "--force"
Write-Result -Title "创建 json 配置" -Result $result

# 2. set-value 仅支持 json
Write-Host "设置 json 配置的值: $jsonName app.version = 2.0.0"
$result = Invoke-SecureconfigCommand -Command "set-value" -Arguments $jsonName, "app.version", "2.0.0"
Write-Result -Title "设置 json 配置值" -Result $result

# 3. get-value 仅支持 json
Write-Host "获取 json 配置的值: $jsonName app.version"
$result = Invoke-SecureconfigCommand -Command "get-value" -Arguments $jsonName, "app.version" 
Write-Result -Title "获取 json 配置值" -Result $result

# 4. 创建 text 文件
$textName = "demo_text"
Write-Host "创建 text 文件: $textName"
$result = Invoke-SecureconfigCommand -Command "create" -Arguments $textName, "--type", "text", "--force"
Write-Result -Title "创建 text 文件" -Result $result

# 5. 保存明文内容到 text 文件（直接写入文件）
$textPath = Join-Path "configs" "$textName.txt"
"Hello, SecureConfig!`n这是一个文本文件。" | Out-File -FilePath $textPath -Encoding utf8
Write-Host "已写入明文内容到 $textPath"

# 6. 加密 text 文件
Write-Host "加密 text 文件: $textName"
$result = Invoke-SecureconfigCommand -Command "encrypt" -Arguments $textName, "--type", "text"
Write-Result -Title "加密 text 文件" -Result $result

# 7. 解密 text 文件
Write-Host "解密 text 文件: $textName"
$result = Invoke-SecureconfigCommand -Command "decrypt" -Arguments $textName, "--type", "text"
Write-Result -Title "解密 text 文件" -Result $result

# 8. 创建 binary 文件
$binaryName = "demo_bin"
Write-Host "创建 binary 文件: $binaryName"
$result = Invoke-SecureconfigCommand -Command "create" -Arguments $binaryName, "--type", "binary", "--force"
Write-Result -Title "创建 binary 文件" -Result $result

# 9. 保存明文内容到 binary 文件（写入二进制数据）
$binaryPath = Join-Path "configs" "$binaryName.bin"
$bytes = [byte[]]@(0, 1, 2, 3, 4, 5, 6, 7)
[System.IO.File]::WriteAllBytes($binaryPath, $bytes)
Write-Host "已写入明文内容到 $binaryPath"

# 10. 加密 binary 文件
Write-Host "加密 binary 文件: $binaryName"
$result = Invoke-SecureconfigCommand -Command "encrypt" -Arguments $binaryName, "--type", "binary"
Write-Result -Title "加密 binary 文件" -Result $result

# 11. 解密 binary 文件
Write-Host "解密 binary 文件: $binaryName"
$result = Invoke-SecureconfigCommand -Command "decrypt" -Arguments $binaryName, "--type", "binary"
Write-Result -Title "解密 binary 文件" -Result $result

Write-Host "`n===== 第二部分: 原地加解密操作 (使用 --inplace 参数) =====" -ForegroundColor Cyan

# 12. 创建原地加密演示文件
$inplaceName = "inplace_demo"
$jsonPath = Join-Path "configs" "$inplaceName.json"
$backupPath = Join-Path "configs" "${inplaceName}_backup.json"

Write-Host "创建原地加密演示 json 文件: $inplaceName"
$result = Invoke-SecureconfigCommand -Command "create" -Arguments $inplaceName, "--type", "json", "--force"
Write-Result -Title "创建原地加密演示文件" -Result $result

# 13. 设置演示文件内容
Write-Host "设置演示文件值: $inplaceName"
Invoke-SecureconfigCommand -Command "set-value" -Arguments $inplaceName, "demo.name", "原地加密演示" | Out-Null
$result = Invoke-SecureconfigCommand -Command "set-value" -Arguments $inplaceName, "demo.description", "这是一个测试原地加密功能的文件"

# 14. 解密后备份原始明文文件（用于对比）
$result = Invoke-SecureconfigCommand -Command "decrypt" -Arguments $inplaceName, "--type", "json"
Copy-Item -Path $jsonPath -Destination $backupPath
Write-Result -Title "设置演示文件值" -Result $result
Write-Host "已备份明文文件到 $backupPath"

# 15. 原地加密
Write-Host "原地加密文件: $inplaceName (使用 --inplace 参数)"
$result = Invoke-SecureconfigCommand -Command "encrypt" -Arguments $inplaceName, "--type", "json", "--inplace"
Write-Result -Title "原地加密" -Result $result

# 16. 验证原地加密结果
$encryptedJsonExists = Test-Path -Path (Join-Path "configs" "$inplaceName.json.enc")
$originalJsonExists = Test-Path -Path $jsonPath
Write-Host "加密文件 ($inplaceName.json.enc) 是否存在? $encryptedJsonExists"
Write-Host "原始文件 ($inplaceName.json) 是否存在? $originalJsonExists (原地加密，应该存在)"

# 17. 原地解密
Write-Host "原地解密文件: $inplaceName (使用 --inplace 参数)"
$result = Invoke-SecureconfigCommand -Command "decrypt" -Arguments $inplaceName, "--type", "json", "--inplace"
Write-Result -Title "原地解密" -Result $result

# 18. 验证文件是否相同
$areFilesIdentical = $false
try {
    $file1Content = Get-Content -Path $jsonPath -Raw
    $file2Content = Get-Content -Path $backupPath -Raw
    $areFilesIdentical = ($file1Content -eq $file2Content)
}
catch {
    Write-Host "比较文件时出错: $_" -ForegroundColor Red
}

Write-Host "原地加解密后的文件与原始文件是否相同? $areFilesIdentical"

# 19. 清理演示文件
Write-Host "`n===== 清理演示文件 =====" -ForegroundColor Cyan
$filesToDelete = @($jsonName, $textName, $binaryName, $inplaceName)

foreach ($name in $filesToDelete) {
    Write-Host "删除文件: $name"
    Invoke-SecureconfigCommand -Command "delete" -Arguments $name, "--type", "json" | Out-Null
}

if (Test-Path -Path $backupPath) {
    Remove-Item -Path $backupPath
    Write-Host "已删除备份文件: $backupPath"
}

# 20. 演示 get-value/set-value 仅支持 json 的限制
Write-Host "`n===== 演示 get-value/set-value 仅支持 json 的限制 =====" -ForegroundColor Cyan

Write-Host "尝试对 text 文件使用 get-value (应报错)"
try {
    $result = Invoke-SecureconfigCommand -Command "get-value" -Arguments $textName, "app.version", "--type", "text"
} 
catch {
    $result = @{ status = "error"; message = $_.Exception.Message }
}
Write-Result -Title "get-value 用于 text 类型" -Result $result

Write-Host "尝试对 binary 文件使用 get-value (应报错)"
try {
    $result = Invoke-SecureconfigCommand -Command "get-value" -Arguments $binaryName, "app.version", "--type", "binary"
}
catch {
    $result = @{ status = "error"; message = $_.Exception.Message }
}
Write-Result -Title "get-value 用于 binary 类型" -Result $result

# 计算总耗时
$endTime = Get-Date
$totalTime = ($endTime - $startTime).TotalSeconds
Write-Host "`n全部演示完成，总耗时: $totalTime 秒" -ForegroundColor Green

<#
使用方法:
1. 确保已安装SecureConfig工具
2. 确保PowerShell执行策略允许运行脚本（可能需要：Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned）
3. 运行脚本: ./demo/powershell_demo.ps1
#> 